<template>
  <ContentWrap title="审批">
    <el-descriptions :column="1" class="w-full" border>
      <el-descriptions-item label="业务名称" width="200">
        {{ detailInfo.name }}
      </el-descriptions-item>
      <el-descriptions-item label="业务类型">
        {{ detailInfo.type == 1 ? 'VOS点呼/群呼主叫加白' : '双向回拨号码加白' }}
      </el-descriptions-item>
      <el-descriptions-item label="归属地">
        {{ detailInfo.locationName }}
      </el-descriptions-item>

      <el-descriptions-item label="话术内容">
        {{ detailInfo.speechContent }}
      </el-descriptions-item>
      <el-descriptions-item label="审核状态">
        {{ statusMap[detailInfo.status] }}
      </el-descriptions-item>

      <el-descriptions-item label="加白坐席">
        <el-table
          :data="detailInfo.agentList"
          :stripe="true"
          border
          :show-overflow-tooltip="true"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="坐席工号" align="center" prop="agentNumber" />
          <el-table-column label="双呼主叫手机号" align="center" prop="telephone" width="150" />
          <el-table-column label="真实姓名" align="center" prop="realName">
            <template #default="scope">
              <div :class="scope.row.realName ? '' : 'text-red text-12px'">
                {{ scope.row.realName ?? '请补全姓名' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="身份证号" align="center" prop="idNumber" width="180">
            <template #default="scope">
              <div :class="scope.row.idNumber ? '' : 'text-red text-12px'">
                {{ scope.row.idNumber ?? '请补全身份证' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="点呼主叫加白" align="center" prop="sipCallAuditStatus">
            <template #default="scope">
              <div>
                <el-tag
                  v-if="auditStatusMap[scope.row.sipCallAuditStatus]"
                  :type="auditStatusMap[scope.row.sipCallAuditStatus].type"
                  >{{ auditStatusMap[scope.row.sipCallAuditStatus].text }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="双向回拨加白" align="center" prop="doubleCallAuditStatus">
            <template #default="scope">
              <div>
                <el-tag
                  v-if="auditStatusMap[scope.row.doubleCallAuditStatus]"
                  :type="auditStatusMap[scope.row.doubleCallAuditStatus].type"
                  >{{ auditStatusMap[scope.row.doubleCallAuditStatus].text }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="审核结果" align="center" prop="auditResult"> </el-table-column>
        </el-table>
      </el-descriptions-item>
      <el-descriptions-item label="处理审核">
        <el-button type="success" :disabled="!canHandleApprove" @click="handleAllSuccess"
          >审核通过</el-button
        >

        <el-button type="danger" :disabled="!canHandleApprove" @click="onBeforeFail"
          >不通过</el-button
        >
        <template v-if="detailInfo.type == 1 || detailInfo.type == 2">
          <el-button @click="showNumberList">选择主叫号码</el-button>
          <span v-if="selectedNumber" class="ml-10px"> 已选：{{ selectedNumber.number }} </span>
        </template>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <Dialog title="该归属地下的号码" v-model="numberVisible" width="1200">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form class="mb-10px" :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="选择归属地" prop="locationId">
          <el-cascader
            v-model="queryParams.locationId"
            :options="locationList"
            :props="{ label: 'name', value: 'id' }"
            :show-all-levels="false"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="号码" prop="number">
          <el-input
            v-model="queryParams.number"
            placeholder="请输入号码"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="queryParams.status">
            <el-option label="空闲" :value="0"></el-option>
            <el-option label="已用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table
        border
        :header-cell-style="{ background: '#f0f0f0' }"
        :data="vosNumberList"
        :stripe="true"
        :show-overflow-tooltip="true"
      >
        <el-table-column label="号码" align="center" prop="number" />
        <el-table-column label="占用状态" align="center" prop="status">
          <template #default="scope">
            <div>
              <el-tag v-if="scope.row.status">在用</el-tag>
              <el-tag v-else type="info">空闲</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="在用企业" align="center" prop="tenantId" />

        <el-table-column label="操作" align="center" width="150px">
          <template #default="scope">
            <el-button link type="primary" @click="selectNumber(scope.row)"> 选择 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="vosNumberTotal"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </ContentWrap>
  </Dialog>
</template>

<script setup>
import * as WhiteAuditApi from '@/api/call/whiteaudit'
import * as VosNumberApi from '@/api/call/vosnumber'
import { dateFormatter } from '@/utils/formatTime'
import * as AreaApi from '@/api/system/area'

const message = useMessage()
const auditId = ref(null)
// 审批单详情
const detailInfo = ref({})
const getAuditDetail = async (id) => {
  detailInfo.value = await WhiteAuditApi.getWhiteAudit(id)
}
// 枚举
const statusMap = { 0: '进行中', 1: '审批结束' }

// 操作栏
const { replace } = useRouter()
const { params } = useRoute()
const returnBack = () => {
  replace({ path: '/call/white-audit' })
}

const auditStatusMap = {
  0: { type: 'info', text: '待审批' },
  1: { type: 'success', text: '已加白' },
  2: { type: 'danger', text: '不通过' }
}

// 选择号码
const numberVisible = ref(false)
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const showNumberList = () => {
  numberVisible.value = true
  queryParams.locationId = detailInfo.value.locationId
  queryParams.type = detailInfo.value.type
  handleQuery()
}
const canHandleApprove = computed(() => {
  return multipleSelection.value.length > 0
})
// 号码查询
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  status: 0,
  locationId: ''
})
const vosNumberList = ref([])
const vosNumberTotal = ref(0)
const handleQuery = async () => {
  const { result } = await VosNumberApi.getVosNumberPage(queryParams)
  vosNumberList.value = result.list
  vosNumberTotal.value = result.total
}

const selectedNumber = ref(null)
const selectNumber = (item) => {
  selectedNumber.value = item
  numberVisible.value = false
}

// 审批
const auditResult = ref('')

/**
 *  审核通过/失败的入参：
 *  auditId: 任务id
 *  agentList: [业务坐席数据id， 非坐席原始id]
 *  status: 1-通过；2-不通过
 *  result: 不通过原因
 *  number: 通过时的主叫号码
 */
const agentList = computed(() => {
  return multipleSelection.value.map((v) => v.id)
})
const onBeforeFail = async () => {
  const data = await message.prompt('请输入不通过原因', '审核不通过')
  const { value, action } = data
  if (data.action == 'confirm') {
    auditResult.value = value
    handleAllFail()
  }
}
const handleAllFail = async () => {
  await WhiteAuditApi.submitAgent({
    auditId: auditId.value,
    status: 2,
    result: auditResult.value,
    agentList: agentList.value
  })
  message.success('操作成功')
  getAuditDetail(auditId.value)
}

const handleAllSuccess = async () => {
  if (!selectedNumber.value && detailInfo.value.type == 1) {
    message.error('未选择号码')
    return
  }
  await message.confirm('确定执行【审核通过】')
  await WhiteAuditApi.submitAgent({
    auditId: auditId.value,
    status: 1,
    numberId: selectedNumber.value.id,
    agentList: agentList.value
  })
  // await WhiteAuditApi.updateWhiteAudit({
  //   id: auditId.value,
  //   status: 3,
  //   number: selectNumber.value ? selectNumber.value.number : ''
  // })
  message.success('操作成功')
  getAuditDetail(auditId.value)
}
// 归属地
const locationList = ref([])
const getLocationList = async () => {
  const data = await AreaApi.getAreaTree()
  locationList.value = data.map((i) => {
    i.children = i.children.map((t) => {
      t.children = []
      return t
    })
    return i
  })
}
// 选择归属地
const handleChange = (value) => {
  queryParams.locationId = value[1]
}
onMounted(() => {
  if (params.id) {
    auditId.value = params.id
    getAuditDetail(params.id)
  } else {
    returnBack()
  }
  getLocationList()
})
</script>
<style scoped>
.el-dialog__body {
  padding-top: 0 !important;
}
</style>
